package marcheba.itaka.view;

import marcheba.itaka.DataStore;
import marcheba.itaka.Event;
import marcheba.itaka.ItakaService;
import marcheba.itaka.R;
import marcheba.itaka.UserInfoService;
import marcheba.itaka.entities.Itaka;
import marcheba.itaka.entities.PhoneStatus;
import marcheba.itaka.entities.PhoneStatus.AvailabilityState;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import com.apphance.android.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class ItakaActivity extends Activity {

	enum UserNameStatus {
		OK, WAITING
	}

	private static final String TAG = "ItakaActivity";
	private DataStore dataStorage;
	private Handler handler = new Handler(Looper.getMainLooper()) {

		@Override
		public void handleMessage(Message msg) {
			Event event = Event.getEvent(msg.what);
			switch (event) {
			case NEW_USER:
				onNewUser((String) msg.obj);
				break;
			case UPDATE_VIEW:
				onUpdateView();
				break;
			}
			super.handleMessage(msg);
		}

	};;
	private Messenger mActivity = new Messenger(handler);

	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
			Message msg = Message.obtain(null,
					Event.REGISTER_ACTIVITY.getIndex());
			msg.replyTo = mActivity;
			try {
				mService.send(msg);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public void onServiceDisconnected(ComponentName name) {

			mService = null;
		}

	};

	private Messenger mService;
	private PhoneStatus phoneStatus;

	UserNameStatus userNameStatus = UserNameStatus.OK;

	private TextView userNameView;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Log.i(TAG, "onActivityResult(): requestCode = " + requestCode);

		if (resultCode != RESULT_OK) {
			Log.w(TAG, "onActivityResult(): resultCode = " + resultCode);
			return;
		}

		Bundle bundle;
		bundle = data.getExtras();
		UserInfoService userInfoService = new UserInfoService(
				this.getResources());
		userInfoService.getUserName(bundle.getString(Itaka.AUTH_CODE),
				Message.obtain(handler, Event.NEW_USER.getIndex()));
		userNameStatus = UserNameStatus.WAITING;

		super.onActivityResult(requestCode, resultCode, data);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(TAG, "OnCreate(): savedInstanceState " + savedInstanceState);
		dataStorage = new DataStore(this);

		setContentView(R.layout.itakaactivity);
		Button button = (Button) findViewById(R.id.SignInButton);
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showLoginPage();
			}
		});

	}

	
	private void onNewUser(String userEmail) {
		Log.i(TAG,"onNewUser()");
		if (userEmail == null)
			Log.e(TAG, "OnNewUser: userEmail = " + userEmail);
		phoneStatus.setAvailabilityState(AvailabilityState.UNAVAILABLE);
		phoneStatus.setAccoutnName(userEmail);
		dataStorage.setPhoneStatus(phoneStatus);
		userNameStatus = UserNameStatus.OK;

		onUpdateView();

		try {
			mService.send(Message.obtain(null,
					Event.AVAILABILITY_CHANGE.getIndex()));
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onStart() {
		Log.i(TAG, "OnStart()");

		onUpdateView();

		Intent itakaService = new Intent(this, ItakaService.class);
		startService(itakaService);

		bindService(new Intent(this, ItakaService.class), mConnection,
				Context.BIND_ABOVE_CLIENT);
		
		super.onStart();
	}

	@Override
	protected void onStop() {
		unbindService(mConnection);
		super.onStop();
	}

	public void showLoginPage() {
		Log.i(TAG, "showLoginPage()");
		Intent loginPageIntent = new Intent(this, LoginPageActivity.class);
		startActivityForResult(loginPageIntent, 0);
	}

	private void onUpdateView() {
		Log.i(TAG, "UpdateView");
		TextView statusText = (TextView) findViewById(R.id.StatusText);
		TextView statusLabel = (TextView) findViewById(R.id.textView2);

		statusLabel.setTextColor(Color.LTGRAY);
		statusText.setTextColor(Color.LTGRAY);
		phoneStatus = dataStorage.getPhoneStatus();

		statusText.setText(phoneStatus.getLocationState().getName());

		userNameView = (TextView) findViewById(R.id.UserNameText);
		if (userNameStatus == UserNameStatus.OK) {
			
			if (phoneStatus.getAvailabilityState() == AvailabilityState.AVAILABLE)
			{
				userNameView.setTextColor(Color.RED);
				userNameView.setText("No user");
			}
			else
			{
				userNameView.setTextColor(Color.GREEN);
				userNameView.setText(phoneStatus.getAccoutnName());
			}
		} else {
			userNameView.setTextColor(Color.WHITE);
			userNameView.setText("Waitng for authentication");
		}

	}

}